package com.talent.jiwen.teacher;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.talent.jiwen.HomeFragment;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.home.AddProblemActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.EvaluateListResult;
import com.talent.jiwen.http.result.GroupInfoResult;
import com.talent.jiwen.http.result.TeacherInfoResult;
import com.talent.jiwen.model.GradeInfo;
import com.talent.jiwen.ui.widgets.ChooseGradeDialog;
import com.talent.jiwen.ui.widgets.StarBar;
import com.talent.jiwen.util.DateUtils;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import pl.droidsonroids.gif.GifImageView;
import rx.Observable;

public class TeacherDetailActivity extends BaseActivity {
    @BindView(R.id.headIv)
    ImageView headIv;
    @BindView(R.id.videoPlayer)
    JZVideoPlayerStandard videoPlayer;
    @BindView(R.id.nameTv)
    TextView nameTv;
    @BindView(R.id.desTv)
    TextView desTv;
    @BindView(R.id.teachAgeTv)
    TextView teachAgeTv;
    @BindView(R.id.scoreLayout)
    RelativeLayout scoreLayout;
    @BindView(R.id.priceTv)
    TextView priceTv;
    @BindView(R.id.tagView)
    com.talent.jiwen.ui.widgets.TagView tagView;
    @BindView(R.id.evaluateCountTv)
    TextView evaluateCountTv;
    @BindView(R.id.evaluateScoreTv)
    TextView evaluateScoreTv;
    @BindView(R.id.severRatingBar)
    StarBar severRatingBar;
    @BindView(R.id.serverScoreTv)
    TextView serverScoreTv;
    @BindView(R.id.effectRatingBar)
    StarBar effectRatingBar;
    @BindView(R.id.effectScoreTv)
    TextView effectScoreTv;
    @BindView(R.id.solvedPercentTv)
    TextView solvedPercentTv;
    @BindView(R.id.evaluateRecyclerView)
    RecyclerView evaluateRecyclerView;
    @BindView(R.id.divider)
    View divider;
    @BindView(R.id.collectLayout)
    RelativeLayout collectLayout;
    @BindView(R.id.collectIv)
    ImageView collectIv;
    @BindView(R.id.collectTv)
    TextView collectTv;
    @BindView(R.id.acceptLayout)
    RelativeLayout acceptLayout;
    @BindView(R.id.optionTv)
    TextView optionTv;
    @BindView(R.id.bottomLayout)
    RelativeLayout bottomLayout;
    @BindView(R.id.allEvaluateTv)
    TextView allEvaluateTv;
    @BindView(R.id.loadingView)
    GifImageView loadingView;
    @BindView(R.id.contentLayout)
    RelativeLayout contentLayout;
    @BindView(R.id.userProfileLayout)
    LinearLayout userProfileLayout;
    @BindView(R.id.userProfileTv)
    TextView userProfileTv;

    private String teacherId;
    private String orderId;
    private static final String PARAM_TEACHER_ID = "param.teacher.id";
    private static final String PARAM_ORDER_ID = "param.order.id";

    //收藏状态
    private int collectStatus;
    private static final int unCollect = 0;
    private static final int collected = 1;

    //详情类型
    private int detailType;
    public static int TYPE_ACCEPT_COURSE = 1;//接受教师
    public static int TYPE_ASK_PROBLEM = 2;//向教师提问
    private static final String PARAM_DETAIL_TYPE = "param.detail.type";

    private List<EvaluateListResult.Evaluate> evaluateList = new ArrayList<>();

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_teacher_detail;
    }

    @Override
    public String titleName() {
        return getString(R.string.teacher_detail);
    }

    @Override
    protected void initData() {

        contentLayout.setVisibility(View.GONE);
        loadingView.setVisibility(View.VISIBLE);

        teacherId = getIntent().getStringExtra(PARAM_TEACHER_ID);
        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);

        detailType = getIntent().getIntExtra(PARAM_DETAIL_TYPE , 1);

        if (detailType == TYPE_ACCEPT_COURSE){
            optionTv.setText("接受课程");
        }else if (detailType == TYPE_ASK_PROBLEM){
            optionTv.setText("发起提问");
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        evaluateRecyclerView.setLayoutManager(layoutManager);
        evaluateRecyclerView.setAdapter(new CommonAdapter<EvaluateListResult.Evaluate>(this , R.layout.item_teacher_evaluate , evaluateList){

            @Override
            protected void convert(ViewHolder holder, EvaluateListResult.Evaluate evaluate, int position) {
                ImageView studentHeadIv = holder.getView(R.id.studentHeadIv);
                ImageUtil.loadCircleImage(TeacherDetailActivity.this , evaluate.getStudentHeadImage() , studentHeadIv);
                holder.setText(R.id.studentNameTv , evaluate.getStudentName());
                StarBar effectStarBar = holder.getView(R.id.effectRatingBar);
                StarBar serverStarBar = holder.getView(R.id.serverRatingBar);

                LinearLayout starLayout = holder.getView(R.id.starLayout);
                LinearLayout solveLayout = holder.getView(R.id.solveLayout);

                if (evaluate.getSolveStatus() == 1){
                    starLayout.setVisibility(View.VISIBLE);
                    solveLayout.setVisibility(View.GONE);

                    effectStarBar.setIntegerMark(false);
                    effectStarBar.setCanTeach(false);
                    effectStarBar.setStarMark(Float.parseFloat(evaluate.getEffectScore()));

                    serverStarBar.setIntegerMark(false);
                    serverStarBar.setCanTeach(false);
                    serverStarBar.setStarMark(Float.parseFloat(evaluate.getServeScore()));
                }else{
                    starLayout.setVisibility(View.GONE);
                    solveLayout.setVisibility(View.VISIBLE);
                }

                holder.setText(R.id.timeTv , DateUtils.ms2Date1(evaluate.getCreateTime()));
                holder.setText(R.id.contentTv ,  evaluate.getStudentEvaluation());

                View divider = holder.getView(R.id.divider);

                if (position == evaluateList.size() - 1){
                    divider.setVisibility(View.GONE);
                }else{
                    divider.setVisibility(View.VISIBLE);
                }
            }
        });

        getTeacherDetail();
//        getTeacherEvaluationList();

    }

    @OnClick({R.id.collectLayout, R.id.acceptLayout , R.id.allEvaluateTv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.collectLayout:
                if(collectStatus == unCollect){
                    //未收藏
                    collectTeacher();
                }else if (collectStatus == collected){
                    //已收藏
                    cancelCollectTeacher();
                }
                break;
            case R.id.acceptLayout:
                if(detailType == TYPE_ACCEPT_COURSE){
                    //接受课程
                    acceptTeacher();
                }else if(detailType == TYPE_ASK_PROBLEM){
                    //提问前如果没有选择过年级，提示用户选择年级
                    if (SPUtil.intOut(SPConstant.SELECT_GRADE) == 0){
                        ChooseGradeDialog gradeDialog=new ChooseGradeDialog(TeacherDetailActivity.this ,new ChooseGradeDialog.OnTagClickListener() {
                            @Override
                            public void onClick(Dialog dialog, GradeInfo gradeInfo) {
                                //保存选中的年级ID
                                SPUtil.intIn(SPConstant.SELECT_GRADE , gradeInfo.getGradeId());
                                EventBus.getDefault().post(HomeFragment.REFRESH_SELECT_GRADE);
                                createGroupInfo();
                            }
                        } , true);
                        gradeDialog.show();
                    }else{
                        //发起提问
                        createGroupInfo();
                    }
                }
                break;
            case R.id.allEvaluateTv:
                TeacherEvaluateActivity.startTeahcerEvaluateActivity(TeacherDetailActivity.this , teacherId);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    /**
     * 获取老师详情
     */
    private void getTeacherDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", teacherId);
        map.put("studentId" , SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().getTeacherDetailInfo(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<TeacherInfoResult>(TeacherDetailActivity.this) {
            @Override
            protected void _onNext(TeacherInfoResult teacherInfoResult) {
                TeacherInfoResult.TeacherInfo data = teacherInfoResult.getTeacherInfo();

                //个人简介视频
                if (Validators.isEmpty(data.getPersonalProfile())){
                    videoPlayer.setVisibility(View.GONE);
                }else{
                    if (data.getVideoExamineStatus() == 1){
                        //视频已上传，并且通过审核
                        videoPlayer.setVisibility(View.VISIBLE);

                        videoPlayer.setUp(data.getPersonalProfile() , JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
                        String url = data.getPersonalProfile();
                        if (!url.endsWith(".mp3") && !url.endsWith(".aac") && !url.endsWith(".amr") && !url.endsWith(".wav") && !url.endsWith(".m4a")) {
                            videoPlayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                            setVideoCover(url);
                        } else {
                            videoPlayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                        }
//                        videoPlayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                    }else{
                        //视屏已上传，但是未通过审核，所以显示头像
                        videoPlayer.setVisibility(View.GONE);
                    }
                }

                ImageUtil.loadCorner4Image(TeacherDetailActivity.this , data.getTeacherHeadImage() , headIv);

                //个人简介文字
                if (Validators.isEmpty(data.getUserProfile())){
                    userProfileLayout.setVisibility(View.GONE);
                }else{
                    userProfileLayout.setVisibility(View.VISIBLE);
                    userProfileTv.setText(data.getUserProfile());
                }

                nameTv.setText(data.getTeacherName());
                priceTv.setText(data.getTeachPrice() + "元/分钟");
                collectStatus = data.getCollectStatus();

                effectRatingBar.setIntegerMark(false);
                effectRatingBar.setCanTeach(false);
                effectRatingBar.setStarMark(Float.parseFloat(data.getEffectScore()));
                effectScoreTv.setText(data.getEffectScore());

                severRatingBar.setIntegerMark(false);
                severRatingBar.setCanTeach(false);
                severRatingBar.setStarMark(Float.parseFloat(data.getServeScore()));
                serverScoreTv.setText(data.getServeScore());

                float score = (Float.parseFloat(data.getEffectScore()) +Float.parseFloat(data.getServeScore())) / 2;
                evaluateScoreTv.setText(score + "");
                desTv.setText("评分 " + score +  "  解决次数 " + data.getSolveCount());
                teachAgeTv.setText("教龄 " + data.getTeachAge() + "年");
                solvedPercentTv.setText((data.getSolvePercent() * 100)+ "%");
                evaluateCountTv.setText(data.getEvaluationCount() + "评价");

                tagView.bindData(data.getTagInfo());

                if (data.getCollectStatus() == 0){
                    //未收藏
                    collectIv.setImageResource(R.mipmap.iv_un_collect);
                    collectTv.setText("收藏");
                }else{
                    //已收藏
                    collectIv.setImageResource(R.mipmap.iv_collected);
                    collectTv.setText("已收藏");
                }

                //评价信息
                if(null != data.getEvaluation()){
                    evaluateList.clear();
                    evaluateList.add(data.getEvaluation());
                    evaluateRecyclerView.getAdapter().notifyDataSetChanged();

                    if (data.getEvaluationCount().equals("1")){
                        allEvaluateTv.setVisibility(View.GONE);
                    }else{
                        allEvaluateTv.setVisibility(View.VISIBLE);
                        allEvaluateTv.setText("查看全部("+ data.getEvaluationCount() +")");
                    }

                }else{
                    allEvaluateTv.setVisibility(View.GONE);
                }

                loadingView.setVisibility(View.GONE);
                contentLayout.setVisibility(View.VISIBLE);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }


    /**获取老师的评价列表
     *
     */
//    private void getTeacherEvaluationList(){
//        Map<String, String> map = new HashMap<>();
//        map.put("teacherId", teacherId);
//        map.put("startIndex" , "1");
//
//        Observable observable = ApiFactory.getEducationApiSingleton().getTeacherEvaluationList(SPUtil.stringOut(SPConstant.TOKEN), map);
//        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<EvaluateListResult>(TeacherDetailActivity.this) {
//            @Override
//            protected void _onNext(EvaluateListResult result) {
//                if (!Validators.isEmpty(result.getEvaluationList())){
//                    evaluateList.clear();
//                    evaluateList.add(result.getEvaluationList().get(0));
//                    evaluateRecyclerView.getAdapter().notifyDataSetChanged();
//                    if (result.getEvaluationList().size() > 1){
//                        allEvaluateTv.setVisibility(View.VISIBLE);
//                    }else{
//                        allEvaluateTv.setVisibility(View.GONE);
//                    }
//                }else{
//                    allEvaluateTv.setVisibility(View.GONE);
//                }
//            }
//
//            @Override
//            protected void _onError(String message) {
//                showToast(message);
//            }
//        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);
//    }

    /**进入发起提问之前先创建群组
     *
     */
    private void createGroupInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().createGroupInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<GroupInfoResult>(TeacherDetailActivity.this) {
            @Override
            protected void _onNext(GroupInfoResult groupInfoResult) {
                String groupId = groupInfoResult.getGroupId();
                boolean hasOrderNow = false;
                if (groupInfoResult.getExistImmediateStatus() == 0){
                    hasOrderNow = false;
                }else{
                    hasOrderNow = true;
                }
                AddProblemActivity.startAddProblemActivity(TeacherDetailActivity.this , groupId , groupInfoResult.getAvailableCouponCount()
                        , hasOrderNow  , "" , teacherId);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }


    /**
     * 接受教师
     */
    private void acceptTeacher() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", teacherId);
        map.put("orderId", orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().acceptTeacher(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(TeacherDetailActivity.this) {
            @Override
            protected void _onNext(Void v) {
                EventBus.getDefault().post(OrderedTeacherListActivity.EVENT_FINISH_ACTIVITY);
                EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);
                EventBus.getDefault().post(CourseWaitListFragment.REFRESH_COURSE_WAIT_LIST);
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    /**
     * 收藏教师
     */
    private void collectTeacher() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", teacherId);
        map.put("studentId", SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().collectTeacher(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(TeacherDetailActivity.this) {
            @Override
            protected void _onNext(Void v) {
                showToast("收藏成功");
                collectIv.setImageResource(R.mipmap.iv_collected);
                collectTv.setText("已收藏");
                collectStatus = 1;
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);

    }

    /**
     * 取消收藏教师
     */
    private void cancelCollectTeacher() {
        Map<String, String> map = new HashMap<>();
        map.put("teacherId", teacherId);
        map.put("studentId", SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().cancelCollectTeacher(SPUtil.stringOut(SPConstant.TOKEN), map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(TeacherDetailActivity.this) {
            @Override
            protected void _onNext(Void v) {
                showToast("取消收藏成功");
                collectIv.setImageResource(R.mipmap.iv_un_collect);
                collectTv.setText("收藏");
                collectStatus = 0;
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);

    }

    /**设置视频封面
     *
     * @param url
     */
    Bitmap bitmap;
    private void setVideoCover(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever retr = new MediaMetadataRetriever();
                retr.setDataSource(url, new HashMap<String, String>());
                bitmap = retr.getFrameAtTime();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(bitmap!=null){
                            videoPlayer.thumbImageView.setImageBitmap(bitmap);
                        }else{
                            videoPlayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                        }
                    }
                });
            }
        }).start();
    }
    /**
     * 启动该页面
     *
     * @param context
     * @param teacherId
     */
    public static void startTeacherDetailActivity(Context context, int type , String teacherId, String orderId) {
        Intent intent = new Intent();
        intent.setClass(context, TeacherDetailActivity.class);
        intent.putExtra(PARAM_DETAIL_TYPE , type);
        intent.putExtra(PARAM_TEACHER_ID, teacherId);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        context.startActivity(intent);
    }

}
